//
//  ZJChooseHouseInformationController.m
//  这家测试项目
//
//  Created by IOS_DEVELOPER on 2017/6/8.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJChooseHouseInformationController.h"
#import "ZJRoomDetailController.h"
#import "ZJRobRoomLineView.h"
#import "ZJHouseInformationModel.h"
#import "ZJRoomModel.h"
#import "ZJRoomCell.h"
#import "ZJlockRoomVC.h"
#import "ZJShouCangFangYuanVC.h"

#import "ZJShaiXuanVC.h"

@interface ZJChooseHouseInformationController ()<UITableViewDelegate,UITableViewDataSource,ZJRoomCellDelegate,ZJBuyHouseDelegate>{
    NSInteger currentIndex;
    CGPoint point;
    BOOL isShow;
    NSMutableArray * cancelBtnArr;
}
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (strong, nonatomic) ZJHouseInformationModel * houseInforModel;
@property (strong, nonatomic) ZJRoomModel * roomModel;
@property (strong, nonatomic) ZJProjectDetailModel * proModel;
@property (strong, nonatomic) ZJUserModel * userModel;
@property (strong, nonatomic) NSArray * modelArr;
@property (strong, nonatomic) NSArray * floorModelArr;
@property (strong, nonatomic) NSMutableArray * canBuyRoom;
@property (nonatomic,weak) UIButton *Selectbutton;
@property (weak, nonatomic) IBOutlet UIStackView *stackView;
@property (weak, nonatomic) IBOutlet UIView *headView;


@property (weak, nonatomic) IBOutlet UIImageView *topImg;
@property (strong, nonatomic)UIAlertController *alertController;
/**<重置数组>*/
@property (strong, nonatomic) NSMutableArray * updArr;
@property (strong, nonatomic) NSMutableArray * updataModelArr;
@property (strong, nonatomic) NSString * backStr;
/*底部按钮*/
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *bottomBtn;
@property (strong, nonatomic) UIButton * btBtn;
@end

@implementation ZJChooseHouseInformationController

-(ZJProjectDetailModel *)proModel{

    if (!_proModel) {
        _proModel = GET_PROJECTINFO;
    }
    return _proModel;
}

-(ZJUserModel *)userModel{
    
    if (!_userModel) {
        _userModel = GET_USERINFO;
    }
    return _userModel;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataBack:) name:@"dataBack" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updata:) name:@"updata" object:nil];
}
#pragma mark - **************通知
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"dataBack" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updata" object:nil];
}

-(void)updata:(NSNotification *)notification{

    self.updArr =[notification.object[@"arr"] copy];
    self.updataModelArr = [NSMutableArray new];

    if (self.updArr.count > 0) {
        
        NSString * str = self.updArr[0];
        NSString * str1;
        NSString * str2;
        if (self.updArr.count == 2) {
            str1 = self.updArr[1];
        }
        if (self.updArr.count == 3) {
            str2 = self.updArr[2];
        }
        
        for (ZJCeillingsModel * celModel in self.modelArr) {
            NSMutableArray * updArr1 = [NSMutableArray new];

            NSArray * roomArr = [ZJRoomModel mj_objectArrayWithKeyValuesArray:celModel.houses];
            for (ZJRoomModel * roomModel in roomArr) {
                
                NSArray * sxArr = [NSArray arrayWithObjects:roomModel.layout,roomModel.house_area_circle,roomModel.house_orientation, nil];
                if (str && (!str1 & !str2)) {
                    if ([sxArr containsObject:str]) {
                        if ([celModel.ceiling_name isEqualToString:roomModel.ceiling_name]) {
                            [updArr1 addObject:roomModel];
                        }
                    }
                }
                if (str && str1 && !str2) {
                    if ([sxArr containsObject:str] && [sxArr containsObject:str1]) {
                        if ([celModel.ceiling_name isEqualToString:roomModel.ceiling_name]) {
                            [updArr1 addObject:roomModel];
                        }
                    }
                }
                if (str && str1 && str2) {
                    if ([sxArr containsObject:str] && [sxArr containsObject:str1] && [sxArr containsObject:str2]) {
                        if ([celModel.ceiling_name isEqualToString:roomModel.ceiling_name]) {
                            [updArr1 addObject:roomModel];
                        }
                    }
                }

                if (updArr1.count > 0) {
                    celModel.houses = updArr1;
                    if (![self.updataModelArr containsObject:celModel]) {
                        [self.updataModelArr addObject:celModel];
                    }
                }
            }
        }

    
    if (!self.updataModelArr || self.updataModelArr.count < 1) {
        
        [HUD showErrorMsg:@"暂无此房型"];
        
    }else{
        self.modelArr = [self.updataModelArr copy];
        [self.tableview reloadData];
       }
    }
}

-(void)dataBack:(NSNotification*)notification{
    NSString * str =notification.object[@"backStr"];
    isShow = NO;
    self.updArr = nil;
    if ([str isEqualToString:@"全部"]) {
        self.modelArr = [ZJCeillingsModel mj_objectArrayWithKeyValuesArray:self.unModel.ceilings];
        [self.tableview reloadData];
    }else{
    [self upRooms];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitView];
    cancelBtnArr = [NSMutableArray new];
    self.btBtn = self.bottomBtn[3];
    [self.btBtn setBackgroundColor:[Utils colorWithHexString:allConstHexColor]];
    if (self.view.height <= 568) {
        for (UIButton * btn in self.bottomBtn) {
            btn.imageEdgeInsets = UIEdgeInsetsMake(0, 25.3, 26, 0);
        }
    }
    
    CGFloat height = SCREEN_WIDTH / 16;
    self.headView.sd_layout.leftSpaceToView(self.view, 0).topSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).heightIs(height * 9);
    self.topImg.sd_layout.leftSpaceToView(self.headView, 0).topSpaceToView(self.headView, 0).rightSpaceToView(self.headView, 0).bottomSpaceToView(self.headView, 0);
    self.tableview.sd_layout.leftSpaceToView(self.view, 0).topSpaceToView(self.headView, 0).rightSpaceToView(self.view, 0).bottomSpaceToView(self.stackView, 2);
    self.stackView.sd_layout.leftSpaceToView(self.view, 0).topSpaceToView(self.tableview, 2).rightSpaceToView(self.view, 0).heightIs(72);
    [self.view setupAutoHeightWithBottomView:self.stackView bottomMargin:0];
//    if (SCREEN_WIDTH > 320) {
//        self.tableview.sd_layout.leftSpaceToView(self.view, 0).topSpaceToView(self.topImg, 0).rightSpaceToView(self.view, 0).bottomSpaceToView(self.stackView, 0);
//        [self.view setupAutoHeightWithBottomView:self.stackView bottomMargin:0];
//    }
    [self.tableview reloadData];
}

#pragma mark - ***初始化视图设置
-(void)InitView{
    self.title = self.titleStr?:@"预选户型";
    self.modelArr = [ZJCeillingsModel mj_objectArrayWithKeyValuesArray:self.unModel.ceilings];
    for (UIButton * btn in self.bottomBtn) {
        if ([btn.titleLabel.text isEqualToString:@"全部"]) {
            self.btBtn = btn;
            self.backStr = @"全部";
        }
    }
    [self.topImg sd_setImageWithURL:[NSURL URLWithString:_deModel.pic_url?:@""] placeholderImage:[UIImage imageNamed:kDefaultImageName]];

}

#pragma mark - ***UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWitMsg:kNoDataImgName ifNecessaryForRowCount:self.modelArr.count];
    return self.modelArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZJRoomCell class]) bundle:nil] forCellReuseIdentifier:CellIdentifier];
    ZJRoomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[ZJRoomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.tag = indexPath.row;
    self.celModel = self.modelArr[indexPath.row];
    cell.model = self.celModel;
    cell.delegate = self;
    [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)onClickRoom:(ZJRoomModel *)roomDict{
    NSLog(@"点击了%@-%@,%@(室)",roomDict.building_name,roomDict.building_name,roomDict.house_name);
     ZJRoomDetailController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"ZJRoomDetailController"];
    ZJHousePreselectionModel * model = self.deModel;
     vc.deModel = model;
     vc.model = roomDict;
     vc.proModel = self.proModel;
     vc.userModel = self.userModel;
     vc.delegate = self;

    [self presentSemiViewController:vc];

}
#pragma mark - ************底部按钮
- (IBAction)allRoomBtn:(UIButton *)sender {
    if (!sender.selected) {
        self.btBtn.selected = NO;
        [self.btBtn setTitleColor:[UIColor lightGrayColor] forState:0];
        [self.btBtn setBackgroundColor:[UIColor whiteColor]];
        [self.btBtn setImage:[UIImage imageNamed:@"zxgf_icon_kx"] forState:0];
        
        sender.selected = YES;
        [sender setTitleColor:[UIColor whiteColor] forState:0];
        [sender setBackgroundColor:[Utils colorWithHexString:allConstHexColor]];
        [sender setImage:[UIImage imageNamed:@"zxgf_icon_qb"] forState:0];
        self.btBtn = sender;
        self.backStr = sender.titleLabel.text;
        self.modelArr = [ZJCeillingsModel mj_objectArrayWithKeyValuesArray:self.unModel.ceilings];
        [self.tableview reloadData];
    }
}
- (IBAction)needRoomBtn:(UIButton *)sender {
    if (!sender.selected && ![self.btBtn.titleLabel.text isEqualToString:sender.titleLabel.text]) {
        self.btBtn.selected = NO;
        [self.btBtn setTitleColor:[UIColor lightGrayColor] forState:0];
        [self.btBtn setBackgroundColor:[UIColor whiteColor]];
        [self.btBtn setImage:[UIImage imageNamed:@"zxgf_icon_qbb"] forState:0];
        
        sender.selected = YES;
        [sender setTitleColor:[UIColor whiteColor] forState:0];
        [sender setBackgroundColor:[Utils colorWithHexString:allConstHexColor]];
        [sender setImage:[UIImage imageNamed:@"zxgf_icon_kxb"] forState:0];
        self.btBtn = sender;
        self.backStr = sender.titleLabel.text;
        [self upRooms];
    }

}

- (IBAction)bottomBtn:(UIButton *)sender {
    switch (sender.tag) {
        case 2:
        {
            [self shaixuan];
        }
            break;
        
        case 3:
        {
            ZJShouCangFangYuanVC *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"ZJShouCangFangYuanVC"];
            vc.proModel = self.proModel;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - ************筛选
-(void)shaixuan{

    ZJShaiXuanVC * vc = [[ZJShaiXuanVC alloc]init];
    vc.backStr = self.backStr;
    if (self.updArr) {
        vc.sxArr = self.updArr;
    }

    [self presentViewController:vc animated:YES completion:nil];
}

-(void)buyHouse:(ZJRoomModel *)model{
    [HUD showLoading:@"正在购买..."];
    [self sureBuyHouse:model];
}

//筛选默认房型
-(void)upRooms{
    self.modelArr = [ZJCeillingsModel mj_objectArrayWithKeyValuesArray:self.unModel.ceilings];
    
    self.canBuyRoom = [ZJCeillingsModel mj_objectArrayWithKeyValuesArray:self.unModel.ceilings];
    
    for (int i = 0; i < self.canBuyRoom.count; i ++) {
        ZJCeillingsModel * celmodel = self.canBuyRoom[i];
        NSMutableArray * modelarr = [ZJRoomModel mj_objectArrayWithKeyValuesArray:celmodel.houses];
        
        for (int j = 0; j < modelarr.count; j ++) {
            
            ZJRoomModel * model = modelarr[j];
            if ([model.status integerValue] == 0) {
                [modelarr removeObjectAtIndex:j];
                j --;
                
            }
        }
        
        celmodel.houses = modelarr;
        
        if (modelarr.count < 1) {
            [self.canBuyRoom removeObjectAtIndex:i];
            i --;
        }
    }
    
    self.modelArr = [self.canBuyRoom copy];
     [self.tableview reloadData];
}
-(void)sureBuyHouse:(ZJRoomModel *)model{
    ZJlockRoomVC *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"ZJlockRoomVC"];
    
    NSDictionary *parameter = [LRNetwork requestParameter:@{@"house_id":model.house_id}];
    NSString *url = [LRNetwork requestURL:@"cgi/house_buy.php"];
    
    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        
        [HUD showSucceedMsg:@"抢房成功!"];
        vc.model = model;
        vc.userModel = self.userModel;
        [self.navigationController pushViewController:vc animated:YES];
        
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        
    }];
}
#pragma mark - 补全分隔线左侧缺失
- (void)viewDidLayoutSubviews {
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
@end
